<?php

class Mageex_ExportPdf_Adminhtml_ExportPdfController extends Mage_Adminhtml_Controller_action
{

	protected function _initAction() {
		$this->loadLayout()
			->_setActiveMenu('exportpdf/items')
			->_addBreadcrumb(Mage::helper('adminhtml')->__('Items Manager'), Mage::helper('adminhtml')->__('Item Manager'));
		
		return $this;
	}   
 
	public function indexAction() {
		$this->_initAction()
			->renderLayout();
	}
	public function printAction(){	
		$template = Mage::getModel('core/email_template');
		if($data = $this->getRequest()->getPost()){
			
			if($data['template_pdf'] == 0 && isset($data['template_pdf'])){
				
				$path = 'admin/sales_order_'.$data['type'].'/print';
				$arguments = array($data['type'].'_id'=>$data['id']);
				$url = $this->getUrl('adminhtml/sales_order_'.$data['type'].'/print', array(
					'invoice_id' => $data['id'],
				));
				$this->_redirect( 'adminhtml/sales_order_'.$data['type'].'/print', array(
					'invoice_id' => $data['id']));
				
			}else{
				$vars = array();
				$size = 'a4';
				$orientation = 'portrait';
				$fileName = 'preview_'.date('Y-m-d').'-'.date('H-i-s');
				if($data['id']){
					$templatePdf = Mage::getModel('exportpdf/exportpdf')->getTemplateById($data['template_pdf']);
					
					$data['text'] 	= $templatePdf['content'];
					$size 			= $templatePdf['size'];
					$orientation 	= $templatePdf['orientation'];
					$fileName = $data['type'].'_'.date('Y-m-d').'_'.date('H-i-s');
					
					//$orderId = 1;
					$type = Mage::getModel('sales/order_'.$data['type'])->load($data['id']);
					$orderId = $type->getOrderId();
					$order  = Mage::getModel('sales/order')->load($orderId);
					
					$vars['order']= Mage::getModel('sales/order')->load($orderId);
					//$vars['store']=Mage::app()->getStores();
					$vars['invoice']= $type;
					$paymentBlock   = Mage::helper('payment')->getInfoBlock($order->getPayment())
												->setIsSecureMode(true);
					$paymentBlock->getMethod()->setStore($order->getStore()->getId());
					$vars['billing']      = $order->getBillingAddress();
					$vars['payment_html'] = $paymentBlock->toHtml();
					$template->setDesignConfig(array('area'=>'frontend', 'store'=>$order->getStoreId()));
				}
				
				$template->setTemplateType($data['type']);
				$template->setTemplateText($data['text']);
				$template->setTemplateStyles($data['styles']);
				
				Varien_Profiler::start("email_template_proccessing");
				
				$templateProcessed = $template->getProcessedTemplate($vars, true);

				
				Varien_Profiler::stop("email_template_proccessing");
				
				$loader = Mage::helper('exportpdf/autoloaddompdf');
				//$loader = Mage::helper('exportpdf/autoloaddompdf')->load();
				$templateProcessed = stripslashes($templateProcessed);
				
				$dompdf = new DOMPDF();
				
				$dompdf->load_html($templateProcessed);
				$dompdf->set_paper($size, $orientation);
				$dompdf->render();
				
				$dompdf->stream($fileName.'.pdf');
				
				exit;
			}
		}
		$this->loadLayout()
			->renderLayout();
	}
	public function editAction() {
		$id     = $this->getRequest()->getParam('id');
		$model  = Mage::getModel('exportpdf/exportpdf')->load($id);

		if ($model->getId() || $id == 0) {
			$data = Mage::getSingleton('adminhtml/session')->getFormData(true);
			if (!empty($data)) {
				$model->setData($data);
			}
			
			Mage::register('exportpdf_data', $model);

			$this->loadLayout();
			$this->_setActiveMenu('exportpdf/items');

			$this->_addBreadcrumb(Mage::helper('adminhtml')->__('Item Manager'), Mage::helper('adminhtml')->__('Item Manager'));
			$this->_addBreadcrumb(Mage::helper('adminhtml')->__('Item News'), Mage::helper('adminhtml')->__('Item News'));

			$this->getLayout()->getBlock('head')->setCanLoadExtJs(true);

			$this->_addContent($this->getLayout()->createBlock('exportpdf/adminhtml_exportpdf_edit'));

			$this->renderLayout();
		} else {
			Mage::getSingleton('adminhtml/session')->addError(Mage::helper('exportpdf')->__('Item does not exist'));
			$this->_redirect('*/*/');
		}
	}
 
	public function newAction() {
		$this->_forward('edit');
	}
	
	public function saveAction() {
		if ($data = $this->getRequest()->getPost()) {
			
			$model = Mage::getModel('exportpdf/exportpdf');		
			$data['used_for'] = implode(',', $data['used_for']);
			
			$model->setData($data)
				->setId($this->getRequest()->getParam('id'));
			
			try {
				if ($model->getCreatedTime == NULL || $model->getUpdateTime() == NULL) {
					$model->setCreatedTime(now())
						->setUpdateTime(now());
				} else {
					$model->setUpdateTime(now());
				}	
				 
				
				$model->save();
				Mage::getSingleton('adminhtml/session')->addSuccess(Mage::helper('exportpdf')->__('Item was successfully saved'));
				Mage::getSingleton('adminhtml/session')->setFormData(false);

				if ($this->getRequest()->getParam('back')) {
					$this->_redirect('*/*/edit', array('id' => $model->getId()));
					return;
				}
				$this->_redirect('*/*/');
				return;
            } catch (Exception $e) {
                Mage::getSingleton('adminhtml/session')->addError($e->getMessage());
                Mage::getSingleton('adminhtml/session')->setFormData($data);
                $this->_redirect('*/*/edit', array('id' => $this->getRequest()->getParam('id')));
                return;
            }
        }
        Mage::getSingleton('adminhtml/session')->addError(Mage::helper('exportpdf')->__('Unable to find item to save'));
        $this->_redirect('*/*/');
	}
 
	public function deleteAction() {
		if( $this->getRequest()->getParam('id') > 0 ) {
			try {
				$model = Mage::getModel('exportpdf/exportpdf');
				 
				$model->setId($this->getRequest()->getParam('id'))
					->delete();
					 
				Mage::getSingleton('adminhtml/session')->addSuccess(Mage::helper('adminhtml')->__('Item was successfully deleted'));
				$this->_redirect('*/*/');
			} catch (Exception $e) {
				Mage::getSingleton('adminhtml/session')->addError($e->getMessage());
				$this->_redirect('*/*/edit', array('id' => $this->getRequest()->getParam('id')));
			}
		}
		$this->_redirect('*/*/');
	}

    public function massDeleteAction() {
        $exportpdfIds = $this->getRequest()->getParam('exportpdf');
        if(!is_array($exportpdfIds)) {
			Mage::getSingleton('adminhtml/session')->addError(Mage::helper('adminhtml')->__('Please select item(s)'));
        } else {
            try {
                foreach ($exportpdfIds as $exportpdfId) {
                    $exportpdf = Mage::getModel('exportpdf/exportpdf')->load($exportpdfId);
                    $exportpdf->delete();
                }
                Mage::getSingleton('adminhtml/session')->addSuccess(
                    Mage::helper('adminhtml')->__(
                        'Total of %d record(s) were successfully deleted', count($exportpdfIds)
                    )
                );
            } catch (Exception $e) {
                Mage::getSingleton('adminhtml/session')->addError($e->getMessage());
            }
        }
        $this->_redirect('*/*/index');
    }
	
    public function massStatusAction()
    {
        $exportpdfIds = $this->getRequest()->getParam('exportpdf');
        if(!is_array($exportpdfIds)) {
            Mage::getSingleton('adminhtml/session')->addError($this->__('Please select item(s)'));
        } else {
            try {
                foreach ($exportpdfIds as $exportpdfId) {
                    $exportpdf = Mage::getSingleton('exportpdf/exportpdf')
                        ->load($exportpdfId)
                        ->setStatus($this->getRequest()->getParam('status'))
                        ->setIsMassupdate(true)
                        ->save();
                }
                $this->_getSession()->addSuccess(
                    $this->__('Total of %d record(s) were successfully updated', count($exportpdfIds))
                );
            } catch (Exception $e) {
                $this->_getSession()->addError($e->getMessage());
            }
        }
        $this->_redirect('*/*/index');
    }
  
    protected function _sendUploadResponse($fileName, $content, $contentType='application/octet-stream')
    {
        $response = $this->getResponse();
        $response->setHeader('HTTP/1.1 200 OK','');
        $response->setHeader('Pragma', 'public', true);
        $response->setHeader('Cache-Control', 'must-revalidate, post-check=0, pre-check=0', true);
        $response->setHeader('Content-Disposition', 'attachment; filename='.$fileName);
        $response->setHeader('Last-Modified', date('r'));
        $response->setHeader('Accept-Ranges', 'bytes');
        $response->setHeader('Content-Length', strlen($content));
        $response->setHeader('Content-type', $contentType);
        $response->setBody($content);
        $response->sendResponse();
        die;
    }
	/**
     * Set template data to retrieve it in template info form
     *
     */
    public function defaultTemplateAction()
    {
        $template = $this->_initTemplate('id');
        $templateCode = $this->getRequest()->getParam('code');
		
        $template->loadDefault($templateCode, $this->getRequest()->getParam('locale'));
        $template->setData('orig_template_code', $templateCode);
        $template->setData('template_variables', Zend_Json::encode($template->getVariablesOptionArray(true)));
		
		//print_r($template->getVariablesOptionArray(true));exit;
        
		$templateBlock = $this->getLayout()->createBlock('adminhtml/system_email_template_edit');
		
        $template->setData('orig_template_used_default_for', $templateBlock->getUsedDefaultForPaths(false));

        $this->getResponse()->setBody(Mage::helper('core')->jsonEncode($template->getData()));
    }

    /**
     * Load email template from request
     *
     * @param string $idFieldName
     * @return Mage_Adminhtml_Model_Email_Template $model
     */
    protected function _initTemplate($idFieldName = 'template_id')
    {
        $this->_title($this->__('System'))->_title($this->__('Transactional Emails'));

        $id = (int)$this->getRequest()->getParam($idFieldName);
        $model = Mage::getModel('adminhtml/email_template');
        if ($id) {
            $model->load($id);
        }
        if (!Mage::registry('email_template')) {
            Mage::register('email_template', $model);
        }
        if (!Mage::registry('current_email_template')) {
            Mage::register('current_email_template', $model);
        }
        return $model;
    }
}